package com.hello.sky.interceptor;

import com.hello.sky.constant.JwtClaimsConstant;
import com.hello.sky.context.BaseContext;
import com.hello.sky.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authentication");
        boolean b = JwtUtil.parseJwt(token);
        if (b) {
            log.info("userToken有效");
            Claims claims = JwtUtil.parseJwtThenReturnId(token);
            Long userId = Long.parseLong(claims.get(JwtClaimsConstant.USER_ID).toString());
            BaseContext.setCurrentId(userId);
            return true;
        }else {
            log.info("userToken无效");
            response.setStatus(401);
            response.setHeader("Content-Type", "text/html;charset=UTF-8");
            response.getWriter().write("token无效");
            return false;
        }
    }

}
